package com.syni.mdd.yhd.common.all.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.syni.mdd.sjb.common.component.utils.common.utils.AppConfig;
import com.syni.mdd.sjb.common.component.utils.common.utils.SpringUtils;
import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.yhd.common.all.constants.ResultCode;
import com.syni.mdd.yhd.common.all.constants.ResultMsg;
import com.syni.mdd.yhd.common.all.entity.SystemUser;
import com.syni.mdd.yhd.common.all.entity.user.BmsUserRegisterDisaster;
import com.syni.mdd.yhd.common.all.service.user.BmsUserRegisterDisasterService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @className WeChartLoginUtils
 * @description TOO
 * @Author cfx
 * @DATE 2019/6/24 12:05
 * @VERSION 1.0
 **/
public class WeChartUtils {

    private final static Logger log = LoggerFactory.getLogger(WeChartUtils.class);

    final static int retryNum = 5;
    /**
     * @Description: 获取第三方登录的用户信息
     * @Param:
     * @return:
     * @Author: cfx
     * @Date: 2019/6/24
     */
    public static JSONObject findWeChatUserInfo(String openId, String accessToken){
        JSONObject ret = new JSONObject();
        AtomicInteger atomicInteger = new AtomicInteger();
        String url = "https://api.weixin.qq.com/sns/userinfo";
        Map<String,Object> paramsMap = new HashMap<>();
        paramsMap.put("openid",openId);
        paramsMap.put("access_token",accessToken);
        paramsMap.put("lang","zh_CN");
        while (atomicInteger.getAndIncrement() < retryNum) {
            try {
                String responseBody = RestTemplateUtils.getForEntity(url, paramsMap);
                if (StringUtils.isNotBlank(responseBody)) {
                    JSONObject responseBodyMap = JSON.parseObject(responseBody);
                    if (responseBodyMap.size() > 0) {
                        ret.putAll(responseBodyMap);
                        break;
                    }
                }
            } catch (Exception e) {
                log.error(e.getMessage(),e);
            }
        }
        return ret;
    }

    public static Map<String,Object> addUserToUserSystem(SystemUser user,boolean isRemedy){
        //补偿机制保证一定成功
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("status",false);
        resultMap.put("msg", ResultMsg.HAND_FAIL);
        try {
            //往用户体系注册用户
            String registerUrl = AppConfig.getProperty("syniUserAddress") + "/syni_user/user/wxRegister";
            JSONObject registerResult = JSONObject.parseObject(RestTemplateUtils.postForEntityForJson(registerUrl,user));
            String registerStatus = registerResult.getString("status");
            JSONObject registerData = registerResult.getJSONObject("data");
            if ("00".equals(registerStatus)) {
                log.info("用户体系注册成功");
                resultMap.put("status",true);
                resultMap.put("data",registerData);
            } else if ("30213".equals(registerStatus)) {
                log.info("用户体系注册失败:账号已存在");
                //更新数据
                updateSysUserData(user);
                //获取数据
                resultMap.put("status",true);
                resultMap.put("data",registerData);
            } else if ("30214".equals(registerStatus)) {
                resultMap.put("status",false);
                resultMap.put("data",registerData);
            }
        } catch (Exception e) {
            log.error("调用户体系接口出错：",e.getMessage());
            if(!isRemedy){
                if(!(resultMap.containsKey("status") && (boolean)resultMap.get("status"))){
                    String accountId = UUID.randomUUID().toString().replaceAll("-","");
                    BmsUserRegisterDisasterService bmsUserRegisterDisasterService = (BmsUserRegisterDisasterService) SpringUtils.getBean(BmsUserRegisterDisasterService.class);
                    Map<String,Object> conditionMap = new HashMap<>();
                    conditionMap.put("registerWay",Constants.REGISTER_USER_SYSTEM);
                    conditionMap.put("userId",user.getUserId());
                    conditionMap.put("content",JSON.toJSONString(user));
                    BmsUserRegisterDisaster bmsUserRegisterDisaster = null;
                    List<BmsUserRegisterDisaster> bmsUserRegisterDisasters = bmsUserRegisterDisasterService.getBaseDao().findAll(new SpecificationUtils(conditionMap));
                    if(!(bmsUserRegisterDisasters != null && bmsUserRegisterDisasters.size() > 0)){
                        bmsUserRegisterDisaster = new BmsUserRegisterDisaster();
                        bmsUserRegisterDisaster.setContent(JSON.toJSONString(user));
                        bmsUserRegisterDisaster.setRegisterWay(Constants.REGISTER_USER_SYSTEM);
                        bmsUserRegisterDisaster.setUserId(user.getUserId());
                        bmsUserRegisterDisaster.setNewTime(new Date());
                        bmsUserRegisterDisaster.setError(e.getMessage());
                        bmsUserRegisterDisaster.setAccountId(accountId);
                        bmsUserRegisterDisasterService.getBaseDao().save(bmsUserRegisterDisaster);
                    }else {
                        bmsUserRegisterDisaster = bmsUserRegisterDisasters.get(0);
                    }
                    bmsUserRegisterDisasterService.getBaseDao().save(bmsUserRegisterDisaster);
                    resultMap.put("status",true);
                    JSONObject registerData = new JSONObject();
                    //registerData.put("accountId",accountId);
                    resultMap.put("data",registerData);
                }
            }
        }
        return resultMap;
    }

    public static Map getSysUserData(Map paramMap) {
        Map<String,Object> resultMap = new HashMap<>();
        String getSysUserUrl = AppConfig.getProperty("syniUserAddress") + "/syni_user/user/accountList";
        Map userParams = new HashMap<>();
        userParams.put("pageNo",1);
        userParams.put("pageSize",1);
        userParams.put("selectAll",0);
        userParams.putAll(paramMap);
        String userBody = RestTemplateUtils.postForEntityForJson(getSysUserUrl,userParams);
        if(StringUtils.isNotBlank(userBody)){
            JSONObject userBodyJson = JSON.parseObject(userBody);
            if(userBodyJson.containsKey("status") && ResultCode.CODE_NORMAL.equals(userBodyJson.getString("status"))){
                JSONArray jsonArray = userBodyJson.getJSONArray("data");
                if(jsonArray.size() > 0){
                    resultMap = jsonArray.getJSONObject(0);
                }
            }
        }
        return resultMap;
    }


    public static void updateSysUserData(SystemUser user){
        String registerUrl = AppConfig.getProperty("syniUserAddress") + "/syni_user/user/updateinfoByUid";
        Map<String,Object> updateParams = new HashMap<>();
        updateParams.put("login_name",user.getLoginName());
        updateParams.put("head_img_url",user.getHeadImgUrl());
        updateParams.put("city",user.getCity());
        updateParams.put("unionId",user.getUnionId());
        updateParams.put("province",user.getProvince());
        updateParams.put("country",user.getCountry());
        String responseBody = RestTemplateUtils.postForEntityForJson(registerUrl,updateParams);
        if(StringUtils.isNotBlank(responseBody)){
            JSONObject jsonObject = JSONObject.parseObject(responseBody);
            if(jsonObject.containsKey("status")){
                if(jsonObject.getString("status").equals(ResultCode.CODE_NORMAL)){
                    log.info("用户体系更新成功");
                }else {
                    log.info(responseBody);
                }
            }
        }
    }
    
    public static Map<String,Object> relationWx(SystemUser user){
    	//补偿机制保证一定成功
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("status",false);
        resultMap.put("msg", ResultMsg.HAND_FAIL);
        String error = "";
        Map<String,Object> updateParams = new HashMap<>();
        try {
        	updateParams.put("accountId",user.getAccountId());
        	updateParams.put("login_name",user.getLoginName());
            updateParams.put("head_img_url",user.getHeadImgUrl());
            updateParams.put("city",user.getCity());
            updateParams.put("unionId",user.getUnionId());
            updateParams.put("province",user.getProvince());
            updateParams.put("country",user.getCountry());
            updateParams.put("sex",user.getSex());
            String registerUrl = AppConfig.getProperty("syniUserAddress") + "/syni_user/user/relationWx";
            JSONObject registerResult = JSONObject.parseObject(RestTemplateUtils.postForEntityForJson(registerUrl,updateParams));
            String registerStatus = registerResult.getString("status");
            JSONObject registerData = registerResult.getJSONObject("data");
            if ("00".equals(registerStatus)) {
                log.info("绑定/解绑微信 更新成功");
                resultMap.put("status",true);
                resultMap.put("data",registerData);
            } else if ("30500".equals(registerStatus)) {
                log.info("账号信息不存在");
                resultMap.put("status",false);
                resultMap.put("data",registerData);
            } 
        } catch (Exception e) {
        	error = e.getMessage();
            log.error("调用户体系接口出错："+e.getMessage());
        }
        if(!(resultMap.containsKey("status") && (boolean)resultMap.get("status"))){
//            String accountId = UUID.randomUUID().toString().replaceAll("-","");
            BmsUserRegisterDisaster bmsUserRegisterDisaster = new BmsUserRegisterDisaster();
            bmsUserRegisterDisaster.setAccountId(user.getAccountId());
            bmsUserRegisterDisaster.setContent(JSONObject.toJSONString(updateParams));
            bmsUserRegisterDisaster.setRegisterWay(Constants.WX_BIND_USER_SYSTEM);
            bmsUserRegisterDisaster.setUserId(user.getUserId());
            bmsUserRegisterDisaster.setNewTime(new Date());
            bmsUserRegisterDisaster.setError(error);
            BmsUserRegisterDisasterService bmsUserRegisterDisasterService = (BmsUserRegisterDisasterService) SpringUtils.getBean(BmsUserRegisterDisasterService.class);
            bmsUserRegisterDisasterService.getBaseDao().save(bmsUserRegisterDisaster);
            resultMap.put("status",true);
            JSONObject registerData = new JSONObject();
            resultMap.put("data",registerData);
        }
        return resultMap;
    }

    public static Map<String,Object> registerUserByIosUserId(String iosUserId){
        //补偿机制保证一定成功
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("status",false);
        resultMap.put("msg", ResultMsg.HAND_FAIL);
        try {
            //往用户体系注册用户
            String registerUrl = AppConfig.getProperty("syniUserAddress") + "/syni_user/user/iosRegister";
            Map<String,Object> params = new HashMap<>();
            params.put("iosUserId",iosUserId);
            JSONObject registerResult = JSONObject.parseObject(RestTemplateUtils.postForEntityForJson(registerUrl,params));
            String registerStatus = registerResult.getString("status");
            JSONObject registerData = registerResult.getJSONObject("data");
            if ("00".equals(registerStatus)) {
                log.info("用户体系注册成功");
                resultMap.put("status",true);
                resultMap.put("data",registerData);
            } else if ("30213".equals(registerStatus)) {
                log.info("用户体系注册失败:账号已存在");
                //获取数据
                resultMap.put("status",true);
                resultMap.put("data",registerData);
            } else if ("30214".equals(registerStatus)) {
                resultMap.put("status",false);
                resultMap.put("data",registerData);
            }
        } catch (Exception e) {
            log.error("调用户体系接口出错：",e);
            if(!(resultMap.containsKey("status") && (boolean)resultMap.get("status"))){
                String accountId = UUID.randomUUID().toString().replaceAll("-","");
                BmsUserRegisterDisasterService bmsUserRegisterDisasterService = (BmsUserRegisterDisasterService) SpringUtils.getBean(BmsUserRegisterDisasterService.class);
                Map<String,Object> conditionMap = new HashMap<>();
                conditionMap.put("registerWay",Constants.REGISTER_IOS_LOGIN);
                conditionMap.put("userId",null);
                conditionMap.put("accountId",accountId);
                BmsUserRegisterDisaster bmsUserRegisterDisaster = null;
                List<BmsUserRegisterDisaster> bmsUserRegisterDisasters = bmsUserRegisterDisasterService.getBaseDao().findAll(new SpecificationUtils(conditionMap));
                if(!(bmsUserRegisterDisasters != null && bmsUserRegisterDisasters.size() > 0)){
                    bmsUserRegisterDisaster = new BmsUserRegisterDisaster();
                    Map<String,Object> content = new HashMap<>();
                    content.put("iosUserId",iosUserId);
                    bmsUserRegisterDisaster.setContent(JSON.toJSONString(content));
                    bmsUserRegisterDisaster.setRegisterWay(Constants.REGISTER_IOS_LOGIN);
                    bmsUserRegisterDisaster.setNewTime(new Date());
                    bmsUserRegisterDisaster.setError(e.getMessage());
                    bmsUserRegisterDisasterService.getBaseDao().save(bmsUserRegisterDisaster);
                }else {
                    bmsUserRegisterDisaster = bmsUserRegisterDisasters.get(0);
                }
                bmsUserRegisterDisasterService.getBaseDao().save(bmsUserRegisterDisaster);
                resultMap.put("status",true);
                JSONObject registerData = new JSONObject();
                //registerData.put("accountId",accountId);
                resultMap.put("data",registerData);
            }
        }
        return resultMap;
    }
}
